package com.test.util.ok;

import com.test.dao.BlogDAO;
import com.test.pojo.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author cVzhanshi
 * @create 2021-08-19 0:07
 */
@Service
public class OrderService {

    @Autowired
    private MySnowFlake idGenerator;
    @Autowired
    private BlogDAO blogDAO;
    //按每3个一组分割
    private static final Integer MAX_SEND = 5000;


    public String getIDBySnowFlake() {
        long time1 = System.currentTimeMillis();
        ArrayList<String> strings = new ArrayList<String>();
        HashSet<String> set = new HashSet<String>();
        //新建线程池（5个线程）
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
//
//        for (int i = 1; i <= 100000; i++) {
//            threadPool.submit(() -> {
//                String x = idGenerator.nextId();
//                strings.add(x);
//                Blog blog = new Blog();
//                blog.setId(x);
//                blogDAO.insert(blog);
//            });
//        }
//
//        threadPool.shutdown();

        List<Blog> blogs = new ArrayList<>();
        for (int i = 1; i <= 100000; i++) {
            String x = idGenerator.nextId();
            set.add(x);
            strings.add(x);
            Blog blog = new Blog();
            blog.setId(x);
            blogs.add(blog);
        }
        long time2 = System.currentTimeMillis();
        System.out.println("shijian1:"+(time2-time1));
//计算切分次数
        int limit = (blogs.size() + MAX_SEND - 1) / MAX_SEND;
        //方法二：获取分割后的集合
        List<List<Blog>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> blogs.stream().skip(a * MAX_SEND).limit(MAX_SEND).parallel().collect(Collectors.toList())).collect(Collectors.toList());
        for (List<Blog> blogList : splitList) {
            blogDAO.batchInsert(blogList);
        }

        long time3 = System.currentTimeMillis();
        System.out.println("shijian2:"+(time3-time2));





        return String.valueOf(strings.size()+"===="+set.size());
    }
}
